package com.redis.ratelimit;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2020-10-02 下午4:44
 */
public class SImpleRateLimiter {
    private final Jedis jedis;

    public SImpleRateLimiter(Jedis jedis) {
        this.jedis = jedis;
    }

    public static void main(String[] args) {
        Jedis jedis = new Jedis("10.2.32.104", 6379);
        SImpleRateLimiter limiter = new SImpleRateLimiter(jedis);
        for (int i = 0; i < 20; i++) {
            System.out.println("---------------  " + i + "  ---------------");
            System.out.println(limiter.isActionAllowed("laoqian", "reply", 60, 5));
        }
    }

    public boolean isActionAllowed(String userId, String actionKey, int period, int maxCount) {
        String key = String.format("hist:%s:%s", userId, actionKey);
        long nowTs = System.currentTimeMillis();
        Pipeline pipeline = jedis.pipelined();
        pipeline.multi();
        pipeline.zadd(key, nowTs, "" + nowTs);
        pipeline.zrangeByScore(key, 0, nowTs - period * 1000);
        Response<Long> count = pipeline.zcard(key);
        pipeline.expire(key, period + 1);
        pipeline.exec();
        pipeline.close();
        return count.get() <= maxCount;
    }
}
